package net.ulrice.mdls.server;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import net.ulrice.mdls.services.MdlsService;
import net.ulrice.mdls.services.Settings;
import net.ulrice.mdls.services.SettingsStoreException;

import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;

public class MdlsServerFacadeHandler implements MdlsService.Iface {


	@Override
	public String getMdlsVersion() throws TException {
		return "Meltdown LS - UNVERSIONED";
	}

	@Override
	public Settings loadSettings() throws TException {
		InputStream in = null;
		try {
			TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
			in = new FileInputStream("data/monitor-settings.cfg");
			byte[] data = new byte[in.available()];
			in.read(data);
			Settings settings = new Settings();
			deserializer.deserialize(settings, data);
			return settings;
		} catch(IOException e) {
			throw new TException(e);
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new TException(e);
				}
			}
		}
	}

	@Override
	public void storeSettings(Settings settings) throws SettingsStoreException, TException {
		OutputStream out = null;
		try {
			TSerializer deserializer = new TSerializer(new TBinaryProtocol.Factory());
			out = new FileOutputStream("data/monitor-settings.cfg");
			out.write(deserializer.serialize(settings));
			out.flush();
		} catch(IOException e) {
			throw new TException(e);
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw new TException(e);
				}
			}
		}
	}
}